#!/usr/bin/env python

"""
This tool provide command-line access to provenance-saving functionality
"""

from standard_script_setup import *

from CIME.case       import Case
from CIME.provenance import *
from CIME.utils      import get_lids
from CIME.get_timing import get_timing

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
        usage="""\n{0} <MODE> [<casedir>] [--verbose]
OR
{0} --help

\033[1mEXAMPLES:\033[0m
    \033[1;32m# Save run (timing) provenance for current case \033[0m
    > {0} postrun
""".format(os.path.basename(args[0])),
        description=description,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("mode", choices=("build", "prerun", "postrun"),
                        help="Phase for which to save provenance. "
                        "prerun is mostly for infrastructure testing; "
                        "it does not make sense to store this information manually otherwise")

    parser.add_argument("caseroot", nargs="?", default=os.getcwd(),
                        help="Case directory")

    parser.add_argument("-l", "--lid",
                        help="Force system to save provenance with this LID")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(args, parser)

    return args.mode, args.caseroot, args.lid

###############################################################################
def _main_func(description):
###############################################################################
    mode, caseroot, lid = parse_command_line(sys.argv, description)
    with Case(caseroot, read_only=False) as case:
        if mode == "build":
            expect(False, "Saving build provenance manually is not currently supported "
                   "but it should already always be happening automatically")
            save_build_provenance(case, lid=lid)
        elif mode == "prerun":
            expect(lid is not None, "You must provide LID for prerun mode")
            save_prerun_provenance(case, lid=lid)
        elif mode == "postrun":
            expect(lid is None, "Please allow me to autodetect LID")
            model = case.get_value("MODEL")
            caseid = case.get_value("CASE")
            case.set_value("SAVE_TIMING", True)
            lids = get_lids(case)
            for lid in lids:
                # call get_timing if needed
                expected_timing_file = os.path.join(caseroot, "timing", "{}_timing.{}.{}.gz" .format(model, caseid, lid))
                if (not os.path.exists(expected_timing_file)):
                    get_timing(case, lid)
                save_prerun_provenance(case, lid=lid)
                save_postrun_provenance(case, lid=lid)
        else:
            expect(False, "Unhandled mode '{}'".format(mode))

if __name__ == "__main__":
    _main_func(__doc__)
